package com.ting.realm;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ting.entity.Jwt;

import com.ting.jwt.JwtToken;
import com.ting.mapper.JwtMapper;
import com.ting.untils.JwtUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Service
public class MyRealm extends AuthorizingRealm {


    @Resource
    private JwtMapper jwtMapper;

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        try{
            Jwt user = JwtUtil.getUserFromToken(principals.toString(),JwtUtil.SECRET);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("name",user.getName());
            queryWrapper.eq("password",user.getPassword());
           Jwt jwt1 = jwtMapper.selectOne(queryWrapper);
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.addRole(jwt1.getRoles());
            Set<String> permission = new HashSet<>(Arrays.asList(jwt1.getPermission().split("\\,")));
            simpleAuthorizationInfo.addStringPermissions(permission);
            return simpleAuthorizationInfo;
        }catch (Exception e){
            e.getMessage();
        }
        return null;
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        try{
            Jwt jwt = JwtUtil.getUserFromToken(token,JwtUtil.SECRET);
            if (jwt == null) {
                throw new AuthenticationException("非法token");
            }
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("name",jwt.getName());
            queryWrapper.eq("password",jwt.getPassword());
            Jwt jwt1 = jwtMapper.selectOne(queryWrapper);
            if (jwt1 == null) {
                throw new AuthenticationException("User didn't existed!");
            }

            if (! JwtUtil.verify(token)) {
                throw new AuthenticationException("Username or password error");
            }
            return new SimpleAuthenticationInfo(token, token, "my_realm");
        }catch (Exception e){
            e.getMessage();
        }
        return null;
    }
}

